package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /// 微信接口调用地址
    private static final String WX = "https://api.weixin.qq.com/sns/jscode2session";
    /// 从yml配置文件中获取secret和appid
    @Autowired
    private WeChatProperties weChatProperties;
    /**
     *  登录
     *
     * */
    @Override
    public User userInfoReturn (UserLoginDTO userLoginDTO) throws Exception {
        /// 调用微信接口，获取当前用户的openid
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String res = "";
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        URIBuilder builder = new URIBuilder(WX);
        if(paramMap != null){
            for (String key : paramMap.keySet()) {
                // key value
                builder.addParameter(key,paramMap.get(key));
            }
        }
        URI uri = builder.build();
        HttpGet httpGet = new HttpGet(uri);

        CloseableHttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            /// 获取响应结果
            res = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = jsonObject.getString("openid");
        log.info("获取到的openid:{}",openid);
        /// 判断openid是否为空
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED); //"登录失败"
        }
        /// 判断当前用户是不是新用户
        User user = userMapper.getUserInfo(openid);
        if ( user == null){
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.saveUser(user);
        }
        /// 是新用户就为他自动注册
        return user;
    }
}
